from sqlalchemy.orm import Session
from app.models.ticket import Ticket
from app.schemas.ticket import TicketCreate, TicketUpdate
from typing import List, Optional

# 获取工单通过ID
def get_ticket(db: Session, ticket_id: int):
    return db.query(Ticket).filter(Ticket.id == ticket_id).first()

# 获取工单列表
def get_tickets(db: Session, skip: int = 0, limit: int = 100, issue_id: Optional[int] = None, status: Optional[str] = None):
    query = db.query(Ticket)
    if issue_id:
        query = query.filter(Ticket.issue_id == issue_id)
    if status:
        query = query.filter(Ticket.status == status)
    return query.offset(skip).limit(limit).all()

# 创建工单
def create_ticket(db: Session, ticket: TicketCreate):
    db_ticket = Ticket(
        issue_id=ticket.issue_id,
        case_id=ticket.case_id,
        template=ticket.template,
        attachments=ticket.attachments,
        status=ticket.status
    )
    db.add(db_ticket)
    db.commit()
    db.refresh(db_ticket)
    return db_ticket

# 更新工单
def update_ticket(db: Session, ticket_id: int, ticket: TicketUpdate):
    db_ticket = db.query(Ticket).filter(Ticket.id == ticket_id).first()
    if db_ticket:
        if ticket.issue_id is not None:
            db_ticket.issue_id = ticket.issue_id
        if ticket.case_id is not None:
            db_ticket.case_id = ticket.case_id
        if ticket.template is not None:
            db_ticket.template = ticket.template
        if ticket.attachments is not None:
            db_ticket.attachments = ticket.attachments
        if ticket.status is not None:
            db_ticket.status = ticket.status
        db.commit()
        db.refresh(db_ticket)
    return db_ticket

# 删除工单
def delete_ticket(db: Session, ticket_id: int):
    db_ticket = db.query(Ticket).filter(Ticket.id == ticket_id).first()
    if db_ticket:
        db.delete(db_ticket)
        db.commit()
    return db_ticket